#include <cassert>
#include <exception>
#include <climits>
#include <new>

#include "system.hpp"

System::System(int numOfCompanies):
	numOfCompanies(numOfCompanies),
        games(numOfCompanies),
        companies(numOfCompanies){}

void System::addGame(ID gameId, ID companyId, int rate){
    if ((games.isMember(gameId))|| (companyId < 1 || companyId > numOfCompanies) || !(companies.isSet(companyId)))
        throw FailureException();
    Game newGame(gameId, companyId, rate);
    games.insert(newGame);
    ratedGames.insert(newGame);
}

void System::removeGame(ID gameId){
    if (!(games.isMember(gameId)))
        throw FailureException();
    const Game* gameToRemove = games.find(gameId);
    ratedGames.remove(*gameToRemove);
    games.remove(gameId);
}

int System::getGameCompany(ID gameId){
	if (!(games.isMember(gameId)))
		throw FailureException();
	const Game* game = games.find(gameId);
	return companies.find(game->makerId);
}

void System::mergeCompanies(ID into, ID from){
	try {
		companies.unite(into, from);
	}
	catch (InvlidIdException) {
		throw FailureException();
	}
	catch (InexistentSetException) {
		throw FailureException();
	}
}

int System::getMinIdGameOfRate (int minRate){
	try {
		return ratedGames.findMinFrom(
			getGameForComparison(INT_MIN, minRate));
	}
	catch (NoSuchElementException) {
		throw FailureException();
	}
}
